package cn.lopr.im.android.mvp.view.adapters;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.text.SpannableString;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import cn.lopr.im.android.R;
import cn.lopr.im.android.bean.User;
import cn.lopr.im.android.db.entity.Message;
import cn.lopr.im.android.mvp.view.activities.MainActivity;
import cn.lopr.im.android.utils.EmojiUtil;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * @author shuangyang7
 * @date 2020/12/19 14:36
 */
public class MsgAdapter extends BaseAdapter {

    private LayoutInflater mInflater;

    private Context context;

    private User friend;

    public static final int MESSAGE_FROM = 0;

    public static final int MESSAGE_TO = 1;

    public static final int MESSAGE_TYPE_COUNT = 2;


    @SuppressLint("SimpleDateFormat")
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private Calendar calendar = Calendar.getInstance();

    CircleImageView ivPortrait;
    TextView tvMsg;
    TextView tvName;
    TextView tvDate;

    private List<Message> msg;

    public MsgAdapter(Context context, List<Message> msg, User friend) {
        this.context = context;
        this.msg = msg;
        this.friend = friend;
        mInflater = LayoutInflater.from(this.context);
    }

    public void addMessage(Message msg) {
        this.msg.add(msg);
        Log.i("socket", "addMessage: " + msg.toString());
        notifyDataSetChanged();
    }

    public void addMessage(List<Message> msg) {
        this.msg.addAll(msg);
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        Log.i("socket", "getCount: " + msg);
        return this.msg.size();
    }

    @Override
    public Message getItem(int i) {
        return msg.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public int getItemViewType(int position) {
        if (msg != null && position < msg.size()) {
            if (msg.get(position).getFromUser().equals(MainActivity.user.getPhone())) {
                return MESSAGE_TO;

            } else {
                return MESSAGE_FROM;

            }

        }
        return super.getItemViewType(position);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup viewGroup) {
        Log.i("socket", "getView: " + position);
        int type = getItemViewType(position);
        String name = "";
        Message msg = getItem(position);
        String imgUrl = "";
        switch (type) {
            case MESSAGE_TO:
                convertView = mInflater.inflate(R.layout.list_item_msg_to, null);
                imgUrl = MainActivity.user.getPortrait();
                name = MainActivity.user.getNickname();
                break;
            case MESSAGE_FROM:
                convertView = mInflater.inflate(R.layout.list_item_msg_from, null);
                imgUrl = friend.getPortrait();
                name = friend.getNickname();
                break;
        }

        tvMsg = convertView.findViewById(R.id.tv_msg);
        ivPortrait = convertView.findViewById(R.id.iv_portrait);
        tvName = convertView.findViewById(R.id.tv_name);
        tvDate = convertView.findViewById(R.id.tv_date);

        String str = msg.getMsg();                             //消息具体内容
        String check = "f0[0-9]{2}|f10[0-7]";               //正则达式，用来判断消息内是否有表情表
        SpannableString spannableString = EmojiUtil.getExpressionString(context, str, check);
        //解析消息内容
        tvMsg.setText(spannableString);

        String date = getPositionForSection(position);

        if (getSectionForPosition(date, position)) {
            tvDate.setVisibility(View.VISIBLE);
            tvDate.setText(msg.getDate());
            tvDate.setTextColor(Color.rgb(0, 0, 0));
        } else {
            tvDate.setVisibility(View.GONE);

        }

        if (tvName.getTag() == null) {
            tvName.setText(name);
            tvName.setTag(name);
        }

        Glide.with(context).load(imgUrl).placeholder(R.drawable.default_head_portrait)
                .dontAnimate()
                .into(new SimpleTarget<GlideDrawable>() {
                    @Override
                    public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
                        ivPortrait.setImageDrawable(resource);
                    }

                    @Override
                    public void onLoadFailed(Exception e, Drawable errorDrawable) {
                        super.onLoadFailed(e, errorDrawable);
                        ivPortrait.setImageDrawable(errorDrawable);
                    }
                });

        return convertView;
    }

    public Object[] getSections() {
        return new Object[0];
    }

    public String getPositionForSection(int i) {
        return this.msg.get(i).getDate();
    }

    public boolean getSectionForPosition(String s, int position) {
        if (position == 0) {
            return true;
        }

        try {
            Date current = sdf.parse(s);
            Date before = sdf.parse(this.msg.get(position - 1).getDate());
            long l = current.getTime() - before.getTime();

            return !(l / 1000 / 60 < 5);

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return false;
    }
}
